<template>
<div>
    <div>
        <el-form ref="tform" :rules="producRules" :model='dataForm' label-width="80px" class="load-settings-form">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="产品名称" prop="product_name">
                        <el-input v-model="dataForm.product_name" placeholder="请输入产品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="客户" prop="cust_id">
                        <el-select v-model="dataForm.cust_id" placeholder="请选择客户">
                            <el-option v-for="item in custOptions" :key="item.id" :label="item.company" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分类" prop="categray_id">
                        <el-cascader ref="cateCascader" :options="categrays" v-model="dataForm.categray_id" :props="{ value: 'id', label: 'name', checkStrictly: false,  expandTrigger: 'hover', emitPath: false}" clearable :show-all-levels="true" filterable @change="selectCategraysChange">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="dataForm.remark" placeholder="请输入产品名称"></el-input>
                    </el-form-item>

                </el-col>
                <el-col :span="12">

                    <el-form-item label="产品编号" prop="product_no">
                        <el-input v-model="dataForm.product_no" placeholder="请输入产品编号"></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="unit_id">
                        <el-select v-model="dataForm.unit_id" placeholder="选择单位">
                            <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="销售价" prop="price">
                        <el-input v-model.number="dataForm.price" placeholder="请输入产品价格"></el-input>
                    </el-form-item>

                    <el-form-item label="启用" prop="status">

                        <el-switch v-model="dataForm.status" active-color="#13ce66" inactive-color="#ff4949" on-value="1" off-value="0" @change="changeSwitch(dataForm.status)">
                            >
                        </el-switch>

                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="附件">
                    <el-upload ref="upload" 
                    multiple
                    action="http://120.79.211.38:8000/api/upload" 
                    accept="image/png,image/gif,image/jpg,image/jpeg" 
                    list-type="picture-card" :limit=limitNum name="fileName" 
                    :headers="headers"
                    :file-list="dataForm.imageFiles" 
                    :auto-upload="false" 
                    :on-exceed="handleExceed" 
                    :before-upload="handleBeforeUpload"  
                    :on-change="onChange" 
                    :on-preview="handlePictureCardPreview" 
                    :on-remove="handleRemove" 
                    :on-success="uploadSucess">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
            </el-row>
        </el-form>

    </div>

</div>
</template>

<script>
import {
    getToken
} from '@/utils/auth'

import {
    productInsert,
    categraylist,
    productUpdate
} from '@/api/product';
import {
    getCustList,
    getUnitList
} from '@/api/getData';

export default {
    inject: ['reload'],
    data() {
        return {
            limitNum: 5,
            producRules: {
                product_name: [{
                    required: true,
                    message: '请输入产品名称',
                    trigger: 'blur'
                }, ],
                product_no: [{
                    required: true,
                    message: '请输入产品编号',
                    trigger: 'blur'
                }, ],
                categray_id: [{
                    required: true,
                    message: '请选择产品分类',
                    trigger: 'blur'
                }, ],
                unit_id: [{
                    required: true,
                    message: '请选择产品单位',
                    trigger: 'blur'
                }, ],
                price: [{
                    required: true,
                    message: '请选择产品单个重量',
                    trigger: 'blur'
                },
                ],
                cust_id: [{
                    required: true,
                    message: '请选择客户',
                    trigger: 'blur'
                },]
            },
            dialogVisible: false,
            dialogImageUrl: '',
            // imageFiles:[],
            imageUrls: [],
            custOptions: [],
            unitOptions: [],
            categrays: [],
            isEdit:false
        }
    },
    props: ['dataForm'],
    created() {
        getCustList().then((res) => {
            if (res.code == 200) {
                this.custOptions = res.data.data;
            } else {
                this.$message(res.msg);
            }
        });
        getUnitList().then((res) => {
            if (res.code == 200) {
                this.unitOptions = res.data.data;
            } else {
                this.$message(res.msg);
            }
        });
        categraylist().then((res) => {
            if (res.code == 200) {
                this.categrays = res.data.data;
            } else {
                this.$message(res.msg);
            }
        });
    },
    components: {

    },
    computed: {
        headers() {
            return {
                'Authorization': 'Bearer ' + getToken('Token'), //携带权限参数
            }
        },
    },
    methods: {
        onSubmit(isEdit) {
            // 	this.$refs[tform].validate(async (valid) => {
            //     if(valid){
            //      this.productInsert();
            //     }else {
            // 	this.$notify.error({
            // 		title: '错误',
            // 		message: '请检查输入是否正确',
            // 		offset: 100
            // 	});
            // 	return false;
            // }
            //   });
            this.isEdit = isEdit;
            if (this.dataForm.imageFiles.length > 0) {
                    this.uploadFile();
                }else{
                    this.updateProduct();
                }
         
           
        },
        resetFields() {
            // this.dataForm.imageFiles = [];
            this.$refs.tform.resetFields();
            this.$refs.upload.clearFiles();

        },
        async addproducts() {
            try {
                let params = this.form;
                params.drawingPic = this.form.drawingPicArr.join(',');
                params.samplePic = this.form.samplePicArr.join(',');

                const result = await addproduct(params);
                if (result.code == 200) {
                    this.$message('新增产品成功');
                    this.reload()
                } else {
                    throw new Error('获取数据失败');
                }
            } catch (err) {
                console.log('获取数据失败', err);
            }
        },
        updateProduct() {
            if (this.imageUrls.length > 0) {
              this.dataForm.images = this.imageUrls.join(',');
            }else{
              this.dataForm.images = '';
            }
            let params = this.dataForm;
            console.log(this.dataForm);
            if (this.isEdit) {
 productUpdate(params).then((res) => {
                if (res.code == 200) {
                    this.$refs.upload.clearFiles()
                    this.$emit('updateSuccess')
                }else{
                  this.$message(res.msg);
                }
            });
            }else{
 productInsert(params).then((res) => {
                if (res.code == 200) {
                    this.$refs.upload.clearFiles()
                    this.$emit('updateSuccess')
                }else{
                  this.$message(res.msg);
                }
            });
            }
           
        },
        // 上传文件之前的钩子
        handleBeforeUpload(file) {
            console.log('before')
            if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
                this.$notify.warning({
                    title: '警告',
                    message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
                })
            }
            let size = file.size / 1024 / 1024 / 2
            if (size > 2) {
                this.$notify.warning({
                    title: '警告',
                    message: '图片大小必须小于2M'
                })
            }
        },
        onChange(file, fileList) {
          this.dataForm.imageFiles = fileList  //把当前文件赋值给 fileList 
        },

        // 文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message('最多只能上传5张图片');
        },
        // 文件列表移除文件时的钩子
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        // 点击文件列表中已上传的文件时的钩子
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        uploadSucess(res) {
            console.log(res);
            if (res.code == 200) {
                this.imageUrls.push(res.data);
                if (this.imageUrls.length == this.dataForm.imageFiles.length) {
                    this.updateProduct();
                }
            } else {
                this.$message(res.msg);
            }

        },
        uploadFile(file,fileList) {
            this.$refs.upload.submit()
        },
        selectCategraysChange(data) {
            this.dataForm.categray_id = data;
        },
        changeSwitch(data){
          this.dataForm.status = data;
        }
    }
}
</script>

<style lang="less">
.load-settings-form {
    padding-right: 20px;
    padding-left: 20px;
    // .el-form-item__label {
    //   display: none;
    //   width: 100px !important;
    // }
    // .el-form-item__content {
    //   margin-left: 3px !important;
    //   margin-right: 3px !important;
    // }

    .el-form-item {
        display: inline-block !important;
    }

    // 上传图片框样式
    .el-upload--picture-card {
        border: 1px dashed #13C3C7;
    }

    .el-upload--picture-card:hover {
        border-color: #13C3C7;
        color: #13C3C7;
    }

    .el-upload--picture-card {
        width: 100px;
        height: 100px;
        font-size: 16px !important;
    }

    .el-upload {
        width: 100px;
        height: 100px;
        line-height: 100px;
        font-size: 16px;
    }

    .el-upload-list--picture-card .el-upload-list__item {
        width: 100px;
        height: 100px;
        line-height: 100px;
        font-size: 16px;
    }

    .el-upload-list--picture-card .el-upload-list__item-actions:hover {
        opacity: 1;
        font-size: 16px;
    }

    .el-upload-list--picture-card .el-upload-list__item-thumbnail {
        width: 100px;
        height: 100px;
        line-height: 100px;
        font-size: 16px;
    }

    .avatar {
        width: 100px;
        height: 100px;
    }
}
</style>
